-- ReagentM
-- Created by chendh
-- 试剂工坊模块

module("ReagentM", package.seeall);

-- 配置
local config = {};

-- 所有的试剂信息
local reagentTable = {};

local formulaToReagent = {};

local whenStartDungeon = nil;

-- 商店信息
local shopInfo = {};

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    reagentTable = {};
    formulaToReagent = {};

    -- 转换下shop_goods配置表
    local reagent_CSV = get_reagent_CSV();
    for i = 1, #reagent_CSV do
        -- 解析出商品信息
        local id = reagent_CSV[i].id;
        reagentTable[id] = parseReagent(reagent_CSV[i])

        formulaToReagent[reagentTable[id]["formula"]] = id;
    end

    -- 离开迷宫清除道具
    EventMgr.removeAll("ReagentM");
    EventMgr.register("ReagentM", event.LEAVE_DUNGEON_CLEAR_ITEM, function(para)
        local classId = para.class_id;
        local count = para.count or 0;

        -- 如果清除的是试剂配方
        if classId and formulaToReagent[classId] and count > 0 then
            BuffDataM.set("reagent", formulaToReagent[classId], 1);
            EventMgr.fire(event.ACTIVE_REAGENT, {["id"] = formulaToReagent[classId],})
        end
    end);


    EventMgr.register("ReagentM", event.DUNGEON_AREADY, whenStartDungeon);

    reagent_CSV = {};
end

-- 初始化
function init()
    shopInfo = {};
    loadCsv();
end

-- 解析试剂数据
function parseReagent(info)
    -- 商品
    local arr = string.explode(string.sub(info.goods, 3, -2), ",")
    info.goods = { 1, tonumber(arr[1]), tonumber(arr[2]), }

    -- 价格
    local ret = {}
    local prices = info.price

    local arr = string.explode(string.sub(prices, 3, -2), ",");
    if string.startWith(prices, "1(") then
        -- 物品
        ret = { 1, tonumber(arr[1]), tonumber(arr[2]), }
    else
        -- 属性
        ret = { 2, arr[1], tonumber(arr[2]), }
    end

    info.price = ret;

    return info
end

-- 获取所有激活的试剂
function getAllReagents()
    if reagentTable == nil then
        return {};
    end

    return reagentTable;
end

-- 根据索引获得商店出售物品信息
function getReagentInfo(reagentId)
    if reagentTable == nil then
        return nil;
    end

    return reagentTable[reagentId];
end

-- 获取商品
function queryGoodsInfo(reagentId)
    -- 返回商品
    return reagentTable[reagentId].goods
end

-- 检索商品价格
function queryPrice(reagentId)
    return reagentTable[reagentId].price
end

-- 试剂图纸是否激活
function isReagentActive(reagentId)
    local reagent = ME.user.dbase:query("reagent");
    if reagent and reagent[reagentId] then
        return reagent[reagentId] >= 1;
    else
        return false;
    end
end

-- 是否有图纸激活
function haveReagentActive()
    for id, info in pairs(reagentTable) do
        if isReagentActive(id) then
            return true;
        end
    end

    return false;
end

-- 根据配方id获取试剂商品编号，需一一对应
function getReagentByFormula(formula_id)
    for key, info in pairs(reagentTable) do
        if info["formula"]== formula_id then
            return key;
        end
    end
    return 0;
end

-- 扣除消耗
function doCost(reagentId)
    local info = reagentTable[reagentId];

    -- 没有该商店信息
    if not info then
        return
    end

    local price = info.price;
    local ok = true;
    local prop;
    local cost_num;
    if price[1] == 1 then
        -- 物品
        ItemM.costAmount(ME.user, price[2], price[3]);
    elseif price[1] == 2 then
        -- 属性
        cost_num = price[3];
        -- 降低购买试剂金币消耗的属性
        if price[2] == "money" then
            prop = PropM.combine(ME.user, "reagent_cost", 1);
            cost_num = PropM.apply(prop, cost_num);
        end
        ME.user:costAttrib(price[2], cost_num);
    end
end

-- 判断能否购买物品，只判断价格
function canBuyReagent(reagentId)
    local info = reagentTable[reagentId];

    -- 没有该商店信息
    if not info then
        return "not reagent";
    end

    if isReagentActive(reagentId) ~= true then
        return "not active";   -- 试剂图纸未激活
    end

    local price = info.price;
    local ok = true;
    local prop;
    local cost_num;
    if price[1] == 1 then
        -- 物品
        ok = ItemM.getAmount(ME.user, price[2]) >= price[3]
        if not ok then
            return "item_lack"   -- 物品数量不足
        end
    elseif price[1] == 2 then
        -- 属性
        cost_num = price[3];
        -- 降低购买试剂金币消耗的属性
        if price[2] == "money" then
            prop = PropM.combine(ME.user, "reagent_cost", 1);
            cost_num = PropM.apply(prop, cost_num);
        end
        ok = ME.user.dbase:query(price[2], 0) >= cost_num
        if not ok then
            return price[2] .. "_lack"  -- 属性数量不足
        end
    else
        return false
    end

    return ok
end

-- 检查包裹中是否有试剂配方
function checkReagent()
    local isInDungeon = DungeonM.isInDungeon();
    print("ReagentM.checkReagent, isIndungeon:" .. tostring(isInDungeon));

    -- 还处于迷宫中，不检查
    if isInDungeon then
        return;
    end

    local checkList = {};

    local configReagents = getAllReagents()
    for _, config in pairs(configReagents) do
        local itemId = config["formula"];
        if ItemM.getAmount(ME.user, itemId) > 0 then
            table.insert(checkList, itemId);
        end
    end

    -- 通知服务器检查新的试剂
    if #checkList > 0 then
        Operation.cmd_check_reagent(checkList);
    end
end

-- 判断当前雅典娜是否开放
function isAthenaOpen()
    return ME.user.dbase:query("athena_is_open") == 1;
end

-- 判断是否能够购买雅典娜之泪
function canBuyAthena()

    if not isAthenaOpen() then
        return false;
    end
    if ME.user.dbase:query("gem") < 50 then
        return false;
    end

    return true;
end

-- 购买雅典娜之泪配方
function buyAthenaFormula()

    if not canBuyAthena() then
        return false;
    end

    ME.user:costAttrib("gem", 50);

    local bonus = {1, 9553, 1};

    BonusM.doBonus(bonus, "buy_athena_formula");

    -- 完成对话后抛出捡物品事件
    EventMgr.fire(event.PICK_UP_ITEM, {
        ["bonus"]         = bonus,
        ["pos"]           = 25,
        ["newBonus"]      = true,
        ["type"]          = GRID_TYPE_ITEM,
        ["isItemVisible"] = true,
        ["borrowGrid"]    = true,
    });

    return true;
end

-- 开始迷宫回调(这边处理获得雅典娜之泪)
whenStartDungeon = function()
    -- 层数
    local layer = DungeonM.currentLayer();

    -- 如果当前层数
    if layer ~= 31 then
        return;
    end

    -- 当前未开放
    if not isAthenaOpen() then
        return;
    end

    -- 不是第一次进入（大地之门回退）
    local maxLayer = ME.user.dbase:query("max_dungeon_layer", 0);
    if maxLayer > 31 then
        return;
    end

    -- 已经激活(身上有雅典娜配方)
    if isReagentActive(51) == true or ItemM.getAmount(ME.user, 9553) > 0 then
         return;
    end

    -- 出战史莱姆和链接的史莱姆
    local pet = ME.user:getActivePet();

    -- 圣域斗士
    if pet.classId ~= 46 then
        return;
    end

    -- 随扈
    local lictors = ME.user.dbase:query("lictor_pets") or {};

    local isOk = false;
    -- 扈从
    for _, petId in ipairs(lictors) do
        if petId == 69 then
            -- 雅典娜
            isOk = true;
        end
    end

    if not isOk then
        return;
    end

    -- 标记触发对话(条件符合可以显示对话)
    EventMgr.fire(event.TRIGGER_ATHENE_DIALOG);
end